package com.sch.www.oauth.controller;

import com.sch.www.common.base.BaseController;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Base64;
import java.util.Collections;
import java.util.Map;

@RequestMapping("/v1/pcAdmin")
@RestController
public class NoClientController extends BaseController {
    private String authIp = "http://127.0.0.1:9011/auth/";
    private String clientId = "client1";
    private String clientSecret = "123456";
    private RestTemplate restTemplate = new RestTemplate();


    @RequestMapping("oauth/token")
    public ResponseEntity<ResponseBody<Map>> gesdsdtById(@RequestBody Map<String, String> userNamePassword) {
        MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.put("username", Collections.singletonList(userNamePassword.get("username")));
        body.put("password", Collections.singletonList(userNamePassword.get("password")));
        body.put("grant_type", Collections.singletonList("password"));
        body.put("scope", Collections.singletonList("app"));
        HttpEntity httpEntity = getHttpEntity(body);
        ResponseEntity<Map> responseEntity = restTemplate.exchange(authIp + "oauth/token", HttpMethod.POST, httpEntity, Map.class);

        ResponseEntity<ResponseBody<Map>> bodyResponseEntity = ResponseBody.switchTo(responseEntity);

        return bodyResponseEntity;

    }

    @RequestMapping("oauth/check_token")
    public ResponseEntity<ResponseBody<Map>>  getBsdsdyId(String token) {
        HttpEntity<MultiValueMap> httpEntity = getHttpEntity(null);
        ResponseEntity<Map> responseEntity = restTemplate.exchange(authIp + "oauth/check_token?token=" + token, HttpMethod.GET, httpEntity, Map.class);

        ResponseEntity<ResponseBody<Map>> bodyResponseEntity = ResponseBody.switchTo(responseEntity);

        return bodyResponseEntity;
    }


    private HttpEntity<MultiValueMap> getHttpEntity(MultiValueMap<String, String> body) {
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.put("Authorization", Collections.singletonList("Basic " + Base64.getEncoder().encodeToString((clientId + ":" + clientSecret).getBytes())));
        HttpEntity<MultiValueMap> httpEntity = new HttpEntity(body, headers);
        return httpEntity;
    }


}

